package com.book.util;


import com.book.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author LiJinCheng
 * @Date 2020/11/14 5:44 下午
 * @Version 1.0
 * @package com.book.util
 **/
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private static List<String> passUrl = new ArrayList<>();
    static {
        passUrl.add("/");
        passUrl.add("/index");
        passUrl.add("/getSessionId");
        passUrl.add("/login/index");
        passUrl.add("/register/index");
        passUrl.add("/getVerify");
        passUrl.add("/checkCode");
        passUrl.add("/getCategory");
        passUrl.add("/user/phoneCheck");
        passUrl.add("/user/checkName");
        passUrl.add("/user/checkEmail");
        passUrl.add("/user/login");
        passUrl.add("/user/doRegister");
        passUrl.add("/user/getCookie");
        passUrl.add("/ubook/searchName");
        passUrl.add("/ubook/searchTitle");
        passUrl.add("/ubook/searchCate");
        passUrl.add("/ubook/queryFilter");
        passUrl.add("/favicon.ico");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserDto user = (UserDto) request.getSession().getAttribute("user");
        log.info("===========" + request.getRequestURI());
        log.info("###user:{}",user);
        log.info("###userIsNull:{}",user == null);
        if (user != null) {
            return true;
        } else {
            String string = request.getRequestURI();
            if (passUrl.contains(string)) {
                return true;
            }
            response.sendRedirect(request.getContextPath() + "/login/index");
            return false;
        }
    }
}
